<?php
namespace Swork\Server\Ws;

use Swork\Bean\Holder\ValidateHolder;
use Swork\Server\ArgumentInterface;

/**
 * WebSocket规则验证器
 * Class WsValidator
 * @package Swork\Server\Ws
 */
class WsValidator
{
    /**
     * 检查
     * @param string $cls 请求类
     * @param string $method 请求执行的方法
     * @param ArgumentInterface $argument 传入参数
     * @throws
     */
    public static function check(string $cls, string $method, ArgumentInterface $argument)
    {
        //提取当前类的检验器和方式
        $validate = ValidateHolder::getClass($cls)[$method] ?? false;
        if ($validate == false)
        {
            return;
        }

        //提取规则，并检查
        $rule = $validate['rule'] ?? [];
        if (count($rule) == 0)
        {
            return;
        }

        //根据每个参数处理
        foreach ($rule as $name => $calls)
        {
            //获取数据值
            $val = $argument->get($name);

            //检验当前字段这下所有规则
            foreach ($calls as $call)
            {
                $target = $call['target'];
                $void = $call['void'];
                if (in_array($void, ['Equal', 'Greater', 'GreaterEqual', 'Lesser', 'lesserEqual']))
                {
                    if (isset($call['match'][0]) && $call['match'][0] == '')
                    {
                        $call['val2'] = $call['match'][1] ?? '';
                    }
                    else
                    {
                        $name2 = $call['match'][1] ?? '';
                        $call['val2'] = $argument->get($name2);
                    }
                }
                $void = lcfirst($void);
                $target::$void($name, $val, $call);
            }
        }
    }
}
